package com.douding.file.controller.admin;

import com.douding.server.domain.File;
import com.douding.server.domain.Test;
import com.douding.server.dto.FileDto;
import com.douding.server.dto.ResponseDto;
import com.douding.server.dto.TeacherDto;
import com.douding.server.enums.FileUseEnum;
import com.douding.server.service.FileService;
import com.douding.server.service.TestService;
import com.douding.server.util.Base64ToMultipartFile;
import com.douding.server.util.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/*
    返回json 应用@RestController
    返回页面  用用@Controller
 */
@RequestMapping("/admin/file")
@RestController
public class UploadController {

    private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);
    public  static final String BUSINESS_NAME ="文件上传";
    @Resource
    private TestService testService;

    @Value("${file.path}")
    private String FILE_PATH="D:/upload/";
    @Value("${file.domain}")
    private String FILE_DOMAIN="http://example.com/";

    @Resource
    private FileService fileService;

    @RequestMapping("/upload")
    public ResponseDto upload(@RequestBody FileDto fileDto) throws Exception {

        LOG.info("文件上传开始");

        // 将 Base64 字符串转换为 MultipartFile 对象
        MultipartFile multipartFile = Base64ToMultipartFile.base64ToMultipart(fileDto.getShard());

        if (multipartFile.isEmpty()) {
            throw new Exception("上传文件为空");
        }
        String fileName = multipartFile.getOriginalFilename();
        String filePath = FILE_PATH + fileName;
        multipartFile.transferTo(new java.io.File(filePath));
        fileDto.setPath(filePath);
        fileDto.setName(multipartFile.getOriginalFilename());
        String contentType = multipartFile.getContentType();
        String suffix = "";
        if (contentType != null && !contentType.isEmpty()) {
            suffix = contentType.substring(contentType.lastIndexOf("/") + 1);
        }
        fileDto.setSuffix(suffix);
        fileDto.setSize((int) multipartFile.getSize());
        fileDto.setUse(FileUseEnum.TEACHER.getCode());
        fileService.save(fileDto);
        String fileUrl = FILE_DOMAIN + fileName;
        ResponseDto responseDto = new ResponseDto();
        responseDto.setContent(fileUrl);

        return responseDto;
    }


    //合并分片
    public void merge(FileDto fileDto) throws Exception {
        LOG.info("合并分片开始");
        // 根据文件标识查询数据库记录
        File file = fileService.selectByKey(fileDto.getKey());

        if (file == null) {
            throw new Exception("文件不存在");
        }

// 获取文件路径
        String filePath = fileDto.getPath();

        // 创建文件输出流
        FileOutputStream fos = new FileOutputStream(filePath, true);

        // 遍历分片文件
        for (int i = 0; i < fileDto.getShardIndex(); i++) {
            // 获取分片文件路径
            String shardFilePath = filePath + "_" + i;

            // 创建文件输入流
            FileInputStream fis = new FileInputStream(shardFilePath);

            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len;

            // 读取分片文件并写入合并文件
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            // 关闭文件输入流
            fis.close();

            // 删除分片文件
            java.io.File shardFile = new java.io.File(shardFilePath);
            shardFile.delete();
        }

        // 关闭文件输出流
        fos.close();
        LOG.info("合并分片结束");
    }


    @GetMapping("/check/{key}")
    public ResponseDto check(@PathVariable String key) throws Exception {
        LOG.info("检查上传分片开始：{}", key);

        // 根据文件标识查询数据库记录
        File file = fileService.selectByKey(key);

        if (file == null) {
            throw new Exception("文件不存在");
        }

        // 构建响应对象
        ResponseDto<FileDto> responseDto = new ResponseDto<>();
        FileDto fileDto = new FileDto();
        fileDto.setId(file.getId());
        fileDto.setPath(file.getPath());
        fileDto.setName(file.getName());
        fileDto.setSuffix(file.getSuffix());
        fileDto.setSize(file.getSize());
        fileDto.setUse(file.getUse());
        fileDto.setCreatedAt(file.getCreatedAt());
        fileDto.setUpdatedAt(file.getUpdatedAt());
        fileDto.setShardIndex(file.getShardIndex());
        fileDto.setShardSize(file.getShardSize());
        fileDto.setShardTotal(file.getShardTotal());
        fileDto.setKey(file.getKey());
        responseDto.setContent(fileDto);

        return responseDto;
    }

}//end class
